package com.xdf.whiteaccount.aop;

import com.xdf.whiteaccount.dao.ContactCompanyMapper;
import com.xdf.whiteaccount.entity.ContactCompany;
import com.xdf.whiteaccount.utils.Example;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @program: white-account
 * @description: 往来单位切面
 * @author: 张柯
 * @create: 2021-07-20 12:49
 **/
@Component
@Aspect
@Slf4j
public class ContactCompanyServiceAspect extends AbstractAop {
    @Autowired
    private ContactCompanyMapper contactCompanyMapper;

    @Pointcut("execution(* com.xdf.whiteaccount.service.ContactCompanyService.insert*(..))")
    private void insertCut() {
    }

    @Pointcut("execution(* com.xdf.whiteaccount.service.ContactCompanyService.update*(..))")
    private void updateCut() {
    }

    /**
     * 新增前事件
     *
     * @param joinPoint
     */
    @Before("insertCut()")
    @Transactional(rollbackFor = Exception.class)
    public void beforeInsert(JoinPoint joinPoint) {
        Object param = getParam1(joinPoint);
        if (param instanceof ContactCompany) {
            ContactCompany record = (ContactCompany) param;
            Assert.state(contactCompanyMapper.countByExample(new Example().andEq("company_name", record.getCompanyName())) <= 0, "客户名不允许重复！");
        }
    }

    /**
     * @param joinPoint
     */
    @AfterReturning(value = "updateCut()", returning = "arg")
    @Transactional(rollbackFor = Exception.class)
    public void afterUpdate(JoinPoint joinPoint, int arg) {
        if (arg > 0) {
            Object param = getParam1(joinPoint);
            if (param instanceof ContactCompany) {
                ContactCompany record = (ContactCompany) param;
                if (record.getCompanyName() != null)
                    Assert.state(contactCompanyMapper.countByExample(new Example().andEq("company_name", record.getCompanyName())) <= 1, "客户名不允许重复！");
            }
        }
    }
}
